'''
Created on Dec 1, 2012

@author: quirino
'''
import unittest
from cupy.connection import Connection, AsyncHTTPConnection
from cupy.messages import Request
from time import sleep

class ConnectionTest(unittest.TestCase):
    
    def setUp(self):
        self.cp = Connection()
    
    def test_encode_params(self):
        params = {'q':'house', 'id':(3,34)}
        ep = self.cp._encode_params(params)
        self.assertEquals("q=house&id=3&id=34", ep, 
                          "Expecting q=house&id=3&id=34 got %s" % (ep))
    
    def test_full_url(self):
        params = {'q':'house', 'id':'3'}
        url = "http://localhost:8000"
        full_url = self.cp._full_url(url, params);
        self.assertEquals("http://localhost:8000?q=house&id=3", full_url, 
            "Expecting http://localhost:8000?q=house&id=3 %s" % (full_url))

class AsyncConnectionTest(unittest.TestCase):
    
    def test_exchange(self):
        reqs = [Request(url="http://localhost:8000"),
               Request(url="http://localhost:8000")]
        
        cs = []
        for req in reqs:
            conn = Connection()
            conn.prepare(req)
            cs.append(conn)
        
        async = AsyncHTTPConnection(cs)
        fs = async.exchange()
        self.assertEquals(len(reqs), len(fs))
        
        while not async.isdone(): sleep(0.2)
        
        for c in cs: c.close()
        
        for f in fs:
            resp = f.get()
            self.assertIsNotNone(resp)
            self.assertFalse(resp.get_url() == "" or resp.get_url() is None) 
        
            

if __name__ == '__main__' :
    unittest.main() 